<template>
	<view class="page">
		<uni-nav-bar fixed="true" :title="groupName" backgroundColor="#6869a8" height="120rpx" @clickLeft="back"
			color="white" statusBar="true" @clickRight="more">
			<view slot="left">
				<uni-icons type="back" size="30" color="white"></uni-icons>
			</view>
			<view slot="right">
				<uni-icons type="bars" size="30" color="white"></uni-icons>
			</view>
		</uni-nav-bar>
		<view style="overflow-y: auto;background-color: #F5F5F5;height: auto;">
			<!-- <scroll-view show-scrollbar="true" scroll-y="true" :refresher-enabled="isOpenRefresh" class="sv"
				:style="{'min-height':navHeight+'px'}" :refresher-triggered="triggered" :refresher-threshold="80"
				refresher-background="#f5f5f5" @refresherpulling="onPulling" @refresherrefresh="onRefresh"
				style="height: 100%;"> -->
			<view v-if="noMore" class="noMore">别拉了，没有更多了~</view>
			<view v-for="(message, index) in messageList" :key="index">
				<view v-if="message.fromId == myId" class="messageCard">
					<view class="box">
						<view class="messageHeader-right messageHeader">
							<view class="text-right">
								<text class="name" style="color: #606060;">{{myName}}</text>
								<!-- 								<br />
								<view class="date">
									<uni-dateformat
										:date="message.sendDate>new Date().getTime()?new Date().getTime():message.sendDate"
										:threshold="[60000,3600000]" />
								</view> -->
							</view>
							<image :src="myAvatar" class="avatar"></image>
						</view>
					</view>
					<view class="box">
						<view class="text text-border-right right" style="background-color: #c4c4e8;">
							<emojiText v-if="message.messageType == 3" :richString="message.data" />
							<image class="image" v-if="message.messageType==4" :src="message.data"
								@click="preview(message.data)" mode="widthFix"></image>
							<view class="date rightdate">
								<uni-dateformat
									:date="message.sendDate>new Date().getTime()?new Date().getTime():message.sendDate"
									:threshold="[60000,3600000]" />
							</view>
						</view>
					</view>
				</view>
				<view v-else class="messageCard">
					<view class="box">
						<view class="messageHeader-left messageHeader">
							<image :src="message.user.avatar" class="avatar" @click="watchFriend(message.fromId)" />
							<view class="text-left">
								<text class="name" style="color: #606060;">{{message.user.username}}</text>
								<!-- 								<br />
								<view class="date">
									<uni-dateformat
										:date="message.sendDate>new Date().getTime()?new Date().getTime():message.sendDate"
										:threshold="[60000,3600000]" />
								</view> -->
							</view>
						</view>
					</view>
					<view class="box">
						<view class="text text-border-left left">
							<emojiText v-if="message.messageType ===3" :richString="message.data" />
							<image class="image" v-if="message.messageType===4" :src="message.data"
								@click="preview(message.data)" mode="widthFix"></image>
							<view class="date leftdate">
								<uni-dateformat
									:date="message.sendDate>new Date().getTime()?new Date().getTime():message.sendDate"
									:threshold="[60000,3600000]" />
							</view>
						</view>
					</view>
				</view>
			</view>
			<view :class="[tool||emotion ?'blank_up':'blank']">
			</view>
			<!-- </scroll-view> -->

		</view>

		<view class="footer">
			<view class="bar">
				<view class="input" style="background-color: #efeff7;">
					<input type="text" confirm-type="send" @confirm="sendMessage" v-model="message"
						@focus="emotion = false;tool = false" @keyboardheightchange="scrollBottom" confirm-hold="true"
						hold-keyboard="true" />
				</view>
				<view class="emo" @click="open('emotion')">
					<uni-icons customPrefix="iconfont" type="icon-smile" color="#6869a8" size="40"></uni-icons>
				</view>
				<view class="send" @touchend.prevent="sendMessage" v-if="message.length !== 0">
					发送
				</view>
				<view class="plus" v-if="message.length === 0" @click="open('tool')">
					<uni-icons type="plus" size="40" color="#6869a8"></uni-icons>
				</view>
			</view>
			<view class="drawer" v-if="emotion || tool">
				<view class="emotion" v-if="emotion">
					<swiper :indicator-dots="true" class="swiper">
						<swiper-item v-for="(parentItem, parentIndex) in emoList" :key="parentIndex">
							<view class="swiper-item">
								<image v-for="item in parentItem" :src="item.value | imgSrc" :key="item.value"
									class="image" @click="clickEmoji(item)" mode="aspectFit"></image>
							</view>
						</swiper-item>
					</swiper>
				</view>
				<view class="tool" v-if="tool">
					<view class="card" @click="selectImg">
						<uni-icons customPrefix="iconfont" type="icon-pic" size="45" color="#6869a8"></uni-icons>
						<view class="text">
							图片
						</view>
					</view>
					<view class="card" @click="camera">
						<uni-icons customPrefix="iconfont" type="icon-camera" size="45" color="#6869a8"></uni-icons>
						<view class="text">
							拍摄
						</view>
					</view>
				</view>
			</view>
		</view>
		<u-modal :show="isJoin == -1" title="温馨提示" content="您已退出该群或此群已解散!" width="500rpx" @confirm="back">
		</u-modal>
	</view>
</template>

<script>
	import emojiText from '@/components/emoji-text/emoji-text.vue'
	import util from "@/config/util.js"
	export default {
		components: {
			emojiText
		},
		data() {
			return {
				myId: "",
				myName: "",
				myAvatar: "../../static/logo.png",
				groupId: "",
				groupName: "加载中...",
				noMore: false, //没有更多历史消息了
				emotion: false, //表情栏开关
				tool: false, //工具栏开关
				message: "",
				//表情列表
				emoList: util.emoList,
				scroll_top: false,
				isJoin: 0
			}
		},
		computed: {
			//同步聊天信息
			messageList() {
				// console.log("get messagelist gid:" + this.groupId)
				let index = this.getIndex(this.groupId);
				this.$store.commit("clearUnread", index)
				// console.log(index)
				if (this.scroll_top === true) {
					this.scroll_top = false
				} else
					this.scrollBottom()
				return this.$store.state.chatList[index].messageList
			}
		},
		methods: {
			//选择图片
			selectImg() {
				let self = this
				uni.chooseImage({
					count: 1,
					sourceType: ['album'],
					success(res) {
						// console.log(JSON.stringify(res.tempFilePaths))
						self.uploadImg(res.tempFilePaths[0])
					}
				})
			},
			//照相机拍照发送
			camera() {
				let self = this
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['camera'],
					success(res) {
						self.uploadImg(res.tempFilePaths[0])
					}
				})
			},
			//上传图片
			uploadImg(imgpath) {
				let self = this
				uni.uploadFile({
					name: 'file',
					url: this.baseUrl + '/file/upload',
					filePath: imgpath,
					header: {
						token: uni.getStorageSync("token")
					},
					success(res) {
						// console.log(res)
						let data = JSON.parse(res.data)
						self.sendImage(data.data.url)
					},
					fail() {
						uni.showToast({
							icon: 'error',
							title: "图片发送失败"
						})
					}
				})
			},
			//预览图片
			preview(url) {
				let urls = []
				urls.push(url)
				console.log("preview:" + url)
				uni.previewImage({
					current: 0,
					urls: urls
				})
			},
			//时间戳转换字符串
			getTime(timestamp) {
				return this.$util.convertTime(timestamp);
			},
			//点击表情
			clickEmoji(item) {
				// console.log(item.lable)
				this.message = this.message + item.lable
			},
			//打开扩展栏
			open(s) {
				if (s === 'tool') {
					this.emotion = false
					this.tool = !this.tool
				}
				if (s === 'emotion') {
					this.tool = false
					this.emotion = !this.emotion
				}
				this.scrollBottom()
			},
			//返回
			back() {
				uni.navigateBack({})
			},
			//聊天设置
			more() {
				uni.navigateTo({
					url: "../groupSetting/groupSetting?gid=" + this.groupId
				})
			},
			//发送消息
			sendMessage() {
				console.log(this.message)
				if (this.message === "") {
					uni.showToast({
						icon: "none",
						title: "请输入消息!"
					});
					return;
				}
				let msg = {
					fromId: this.myId,
					toId: this.groupId,
					messageType: 3,
					data: this.message
				}
				this.$socket.send(msg)
				this.message = ""
			},
			//发送图片
			sendImage(url) {
				console.log(url)
				let msg = {
					fromId: this.myId,
					toId: this.groupId,
					messageType: 4,
					data: url
				}
				this.$socket.send(msg)
			},
			//获取历史消息
			getData() {
				// 前端获取数据
				console.log("获取历史数据");
				// console.log(this.getEarlyDate())
				this.$request.TokenRequest({
					url: "/message/getGroupHistoryMessage"
				}, {
					date: this.getEarlyDate(),
					gid: this.groupId
				}).then(res => {
					if (res.state === 200) {
						this.addHistoryMessage(res.data)
						if (res.message === "false") {
							this.noMore = true
							this.isOpenRefresh = false
						}
					}
				})
			},
			//向聊天列表中添加历史信息记录
			addHistoryMessage(messageList) {
				messageList = messageList.reverse()
				let index = this.getIndex(this.groupId)
				this.scroll_top = true
				this.$store.state.chatList[index].messageList.unshift(...messageList)
			},
			//获取本地聊天信息中最早的,以获取历史消息
			getEarlyDate() {
				let index = this.getIndex(this.groupId)
				if (this.$store.state.chatList[index].messageList.length === 0) return new Date().getTime()
				else {
					return new Date(this.$store.state.chatList[index].messageList[0].sendDate).getTime()
				}
			},
			//滑动至底部
			scrollBottom() {
				console.log("滑到底部")
				this.$nextTick(function() {
					uni.pageScrollTo({
						scrollTop: 2000000,
						duration: 200
					})
				})
			},
			//获取该聊天在chatList中的index
			getIndex(id) {
				return util.findGidAndAdd(id)
			},
			//更新,获取好友信息,同时在查询中index为-1时在chatList中新增聊天
			updateGroupInfo(gid) {
				let index = this.getIndex(gid)
				this.$request.TokenRequest({
					url: "/group/getGroupInfo"
				}, {
					gid: gid
				}).then(res => {
					if (res.state === 200 && res.data !== null)
						this.$store.state.chatList[index].group = res.data
				})
			},
			//跳转好友信息页
			watchFriend(id) {
				uni.navigateTo({
					url: "../informationPage/informationPage?id=" + id
				})
			}
		},
		filters: {
			imgSrc(value) {
				return `../../static/emoji/d_${value}.gif`
			}
		},
		onBackPress() {
			let self = this
			// console.log("onback")
			//截取,只留最近12条记录
			let index = this.getIndex(this.groupId)
			let len = self.$store.state.chatList[index].messageList.length
			if (len > 12) {
				self.$store.state.chatList[index].messageList = self.$store.state.chatList[index]
					.messageList.slice(len - 12, len)
			}
			self.$store.commit("storeChatList");
		},
		onPullDownRefresh() {
			if (!this.noMore)
				this.getData()
			uni.stopPullDownRefresh()
		},
		onLoad(option) {
			this.groupId = option.gid
			this.groupName = option.groupName
			this.myId = this.$store.state.userInfo.id
			this.myName = this.$store.state.userInfo.username
			this.myAvatar = this.$store.state.userInfo.avatar
			this.updateGroupInfo(this.groupId, this.$store.state.chatList)
			setTimeout(() => {
				this.scrollBottom()
			}, 1000)
			// this._freshing = false;
		},
		onShow() {
			this.$request.TokenRequest({
				url: "/group/isJoin"
			}, {
				gid: this.groupId
			}).then(res => {
				if (res.state === 200) {
					this.isJoin = parseInt(res.data)
				}
			})
		},
	}
</script>

<style lang="scss" scoped>
	.blank {
		height: 90rpx;
	}

	.blank_up {
		height: 90rpx+420rpx;
	}

	.noMore {
		padding: 20rpx;
		margin: 0 auto;
		text-align: center;
		color: #ACACAC;
		font-size: 30rpx;
	}

	.messageCard {
		padding: 20rpx 10rpx;

		.avatar {
			width: 80rpx;
			height: 80rpx;
			margin: 0 20rpx;
			border-radius: 15rpx;
		}

		.text-right {
			text-align: right;
		}

		.text-left {
			text-align: left;
		}

		.messageHeader {
			display: flex;
			height: 100rpx;
			align-items: center;

			.name {
				font-size: 28rpx;
			}
		}

		.messageHeader-right {
			margin-left: auto;
		}

		.messageHeader-left {
			margin-right: auto;
		}

		.text {
			font-size: 37rpx;
			background-color: #FFFFFF;
			min-width: 270rpx;
			max-width: 370rpx;
			word-break: break-all;
			padding: 12rpx 27rpx;
		}

		.text-border-left {
			border-radius: 7rpx 30rpx 30rpx 30rpx;
		}

		.text-border-right {
			border-radius: 30rpx 7rpx 30rpx 30rpx;
		}

		.box {
			display: flex;
		}

		.image {
			max-width: 370rpx;
			border-radius: 15rpx;
			margin-top: 15rpx;
		}

		.left {
			margin-left: 110rpx;
			margin-right: auto;
		}

		.right {
			margin-right: 110rpx;
			margin-left: auto;
		}

		.date {
			display: inline-block;
			font-size: 23rpx;
			width: 100%;
			text-align: right;
		}

		.leftdate {
			color: #aaabda;
		}

		.rightdate {
			color: #6869a8;
		}
	}

	.footer {
		position: fixed;
		bottom: 0rpx;
		background-color: #FFFFFF;
		width: 100%;
		align-items: center;


		.bar {
			display: flex;
			width: 95%;
			margin: 10rpx 20rpx;
			align-items: center;

			.send {
				display: inline-block;
				width: 100rpx;
				height: 50rpx;
				line-height: 50rpx;
				text-align: center;
				font-size: 33rpx;
				padding: 5rpx 24rpx;
				color: #FFFFFF;
				border-radius: 15rpx;
				background-color: #1299F0;
				margin: 0 5rpx;
			}

			.input {
				display: inline-block;
				padding: 15rpx;
				width: 100%;
				background-color: #f5f5f5;
				border-radius: 15rpx;
			}

			.emo {
				display: inline-block;
				margin: 0 5rpx;
			}

			.plus {
				display: inline-block;
				margin: 0 5rpx;
			}

			/deep/ .uni-input-input {
				font-size: 35rpx !important;
				height: 60rpx !important;
				line-height: 60rpx !important;
			}
		}

		.drawer {
			display: block;
			width: 100%;
			height: 420rpx;

			.image {
				width: 60rpx;
				height: 60rpx;
				padding: 15rpx;
				margin: 10rpx 0;
			}

			.emotion {
				text-align: center;
				height: 100%;

				.swiper {
					height: 100%;
				}
			}

			.tool {
				height: 100%;
				margin: 0 20rpx;

				.card {
					text-align: center;
					height: 100rpx;
					width: 100rpx;
					display: inline-block;
					padding: 30rpx;

					.text {
						margin: 10rpx 0;
						color: #6C6C6C;
						font-size: 25rpx;
					}
				}
			}
		}
	}
</style>
<style>
	page {
		background-color: #f5f5f5;
	}
</style>
